/**
 * 语言切换组合式函数
 * 为页面提供统一的语言切换功能
 */
import { onMounted, onUnmounted } from "vue";
import { useI18n } from "vue-i18n";
import { getSavedLanguage } from "./language";

/**
 * 使用语言切换功能的组合式函数
 * @returns {object} 包含语言相关的方法和状态
 */
export const useLanguage = () => {
  const i18n = useI18n();
  const { t, locale } = i18n;

  // 初始化页面语言设置
  const initPageLanguage = () => {
    const savedLanguage = getSavedLanguage();
    if (locale.value !== savedLanguage) {
      locale.value = savedLanguage;
    }
  };

  // 监听语言切换事件
  const handleLanguageChange = (newLanguage) => {
    if (locale.value !== newLanguage) {
      locale.value = newLanguage;
    }
  };

  // 在组件挂载时初始化语言并监听事件
  onMounted(() => {
    initPageLanguage();
    uni.$on("languageChanged", handleLanguageChange);
  });

  // 在组件卸载时移除事件监听
  onUnmounted(() => {
    uni.$off("languageChanged", handleLanguageChange);
  });

  return {
    t,
    locale,
    i18n,
    initPageLanguage,
    handleLanguageChange,
  };
};
